'
' StoreNuke.Net -  http:'www.storenuke.net
' Copyright (c) 2005
' by Robert J Collins ( info@storenuke.net ) of WillowTree Software, Inc. ( http:'www.willowtreesoftware.com )
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
'

Imports System.Web
Imports System.Data.SqlClient
Imports StoreNuke.StarterKit.Commerce
Imports StoreNuke.StarterKit.Commerce.Components
Imports System.Net
Imports System.IO
Imports System


Public MustInherit Class PayPalCheckOut
    Inherits GatewayControl
    Public ProductID As Integer

    Protected WithEvents ImageButton1 As System.Web.UI.WebControls.ImageButton
    Dim settings As New Hashtable
    Protected WithEvents lblError As System.Web.UI.WebControls.Label
    Dim store As New StoreControlsDB


#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Get gateway settings
        settings = store.GetStoreControlSettings(StoreControlID)

        If (Not Page.IsPostBack) Then
            'Verify the gateway is configured
            LoadAdmin()
        End If

    End Sub

    Private Sub LoadAdmin()
        If (settings("WTPayPalID") = Nothing) Then
            lblError.Text = "Gateway not yet configured.  You cannot checkout!"
            ImageButton1.Visible = False
        Else
            lblError.Text = ""
            ImageButton1.Visible = True
            ImageButton1.ImageUrl = settings("WTPayPalImageURL").ToString()
        End If
    End Sub

    Public Sub ReturnPayPalPost()
        If (settings("WTPayPalID") <> Nothing) Then
            ' build secure PayPal URL
            Dim strPayPalURL As String = ""
            strPayPalURL = "https://www.paypal.com/xclick/business=" & HTTPPOSTEncode(settings("WTPayPalID").ToString())
            strPayPalURL = strPayPalURL & "&item_name=" & HTTPPOSTEncode(settings("WTPayPallCartName").ToString())
            strPayPalURL = strPayPalURL & "&item_number=" & HTTPPOSTEncode(Context.User.Identity.Name)
            strPayPalURL = strPayPalURL & "&quantity=1"
            strPayPalURL = strPayPalURL & "&custom=" & HTTPPOSTEncode(CheckOut.ShipToAddress)
            strPayPalURL = strPayPalURL & "&amount=" & HTTPPOSTEncode(CheckOut.Total)
            strPayPalURL = strPayPalURL & "&currency_code=" & HTTPPOSTEncode(settings("WTPayPalCurrency").ToString())
            strPayPalURL = strPayPalURL & "&return=" & HTTPPOSTEncode("http://" & GetDomainName() & "/Default.aspx?scid=8")
            strPayPalURL = strPayPalURL & "&cancel_return=" & HTTPPOSTEncode("http://" & GetDomainName())
            strPayPalURL = strPayPalURL & "&notify_url=" & HTTPPOSTEncode("http://" & GetDomainName() & "/Gateways/WillowTreeSoftware.PayPal.Gateway/PayPalIPN.aspx")
            strPayPalURL = strPayPalURL & "&undefined_quantity=&no_note=1&no_shipping=1"
            'strPayPalURL = strPayPalURL & "&shipping=" & HTTPPOSTEncode(CheckOut.ShippingAmount)
            'strPayPalURL = strPayPalURL & "&tax=" & HTTPPOSTEncode(CheckOut.Tax)
            Response.Redirect(strPayPalURL)
        End If
    End Sub

    Private Function GetDomainName() As String
        Dim url As String = Request.Url.ToString()
        Return url.Substring(0, url.IndexOf("/"))
    End Function

    Private Sub ImageButton1_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
        Dim ct As New CartProcessingControl
        If (Convert.ToDecimal(CheckOut.Total) = Convert.ToDecimal(0)) Then
            Dim returnValue As Integer = ct.ProcessCart(Convert.ToInt32(CheckOut.ShipToAddress), Context.User.Identity.Name)
            If (returnValue > -1) Then
                CheckOut.CartMessage = "Your order was completed successfully.<br><br>Your order number is: " & returnValue
                ImageButton1.Visible = False
                CheckOut.HidePaymentPanel = True
            Else
                lblError.Text = "Error Processing Cart"
            End If
        Else
            ReturnPayPalPost()
        End If
    End Sub

    ' encodes a URL for posting to an external site
    Public Function HTTPPOSTEncode(ByVal strPost As String) As String
        strPost = Replace(strPost, "\", "")
        strPost = System.Web.HttpUtility.UrlEncode(strPost)
        strPost = Replace(strPost, "%2f", "/")
        HTTPPOSTEncode = strPost
    End Function

End Class
